<template>
	<div>
		<use-table ref="tbl"></use-table>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">标题：</div>
					<el-input v-model="req.title" placeholder="请输入" class="search_input" @change="search" clearable>
					</el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">类型：</div>
					<el-select v-model="req.type" class="search_input" @change="search" clearable>
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">状态：</div>
					<el-select v-model="req.state" class="search_input" @change="search" clearable>
						<el-option v-for="item in stateOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedSearch = !advancedSearch"
					v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedSearch = !advancedSearch" v-if="advancedSearch">
					常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<div>
					<!-- <el-popover :disabled="popoverDisabled" :value="popoverDisabled" placement="left" trigger="click"
						:open-delay="0" :close-delay="50" @show="popoverShow" @after-leave="popoverAfterLeave">
						<el-skeleton :loading="bindsLoading" animated>
							<template slot="template">
								<el-skeleton-item variant="image" style="width: 200px; height: 200px;" />
							</template>
							<template>
								<img :src="wxQrcodeUrl" style="width: 200px;height: 200px;" />
								<div class="center_just">微信扫一扫绑定</div>
								<div class="center_just remark_txt">绑定之后将接收相关消息通知</div>
							</template>
						</el-skeleton>
						<el-button slot="reference" class="batch-btn padding0" @click="binds">批量绑定<span
								v-if="selectDatas.length">×{{selectDatas.length}}</span>
						</el-button>
					</el-popover> -->
					<!-- <el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes">删除</el-button> -->
				</div>
				<!-- <el-button class="add-btn pos_r padding0" icon="iconfont iconxinzeng" @click="toAdd">新增</el-button> -->
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas"
				@selection-change="selectionChange" highlight-current-row>
				<el-table-column type="selection" :selectable="selectable"></el-table-column>
				<el-table-column label="排序" width="200" align="center">
					<template slot-scope="scope">
						<el-input-number size="small" :min="1" v-model="scope.row.sort"
							@change="(newSort, oldSort) => sortChange(newSort, oldSort, scope.row)"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column property="title" label="标题" align="center"></el-table-column>
				<el-table-column label="类型" align="center">
					<template slot-scope="scope">
						<div>{{scope.row.type == 1 ? '管理员' : '用户'}}</div>
					</template>
				</el-table-column>
				<el-table-column label="描述" align="center">
					<template slot-scope="scope">
						<div>{{scope.row.description || '--'}}</div>
					</template>
				</el-table-column>
				<el-table-column label="接收者" align="center">
					<template slot-scope="scope">
						<div class="dflex_level_c">
							<div v-for="(item, i) in scope.row.users" :key="i" class="receive dflex_level_c pos_r">
								<el-avatar :size="30"
									:src="item.headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'">
								</el-avatar>
								<div v-if="!unbindLoading" title="解绑" class="el-icon-minus dflex_c pos_a crpr"
									@click="unbind(scope.row, item)"></div>
								<div v-else class="el-icon-loading dflex_c pos_a"></div>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column property="state" label="状态" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" :content="scope.row.state == '显示' ? '点击隐藏' : '点击显示'"
							placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.state" active-color="#ff6a6c" inactive-color="#bbb"
								:active-value="1" :inactive-value="0" @change="stateChange(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-tooltip v-if="scope.row.type == 1" :open-delay="350" content="绑定" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-popover :ref="'popoverRef'+ scope.row._id" placement="left" trigger="click"
								:open-delay="0" :close-delay="50" @show="bind(scope.row._id)">
								<el-skeleton :loading="bindLoading" animated>
									<template slot="template">
										<el-skeleton-item variant="image" style="width: 200px; height: 200px;" />
									</template>
									<template>
										<img :src="wxQrcodeUrl" style="width: 200px;height: 200px;" />
										<div class="center_just">微信扫一扫绑定</div>
										<div class="center_just remark_txt">绑定之后将接收相关消息通知</div>
									</template>
								</el-skeleton>
								<el-button slot="reference" circle size="medium" icon="el-icon-connection"
									class="table-btn"></el-button>
							</el-popover>
						</el-tooltip>
						<!-- 	<el-tooltip :open-delay="350" content="编辑" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-edit" class="table-btn"
								@click="toEdit(scope.row._id)"></el-button>
						</el-tooltip> -->
						<!-- <el-tooltip :open-delay="350" content="删除" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-delete" class="table-btn"
								@click="remove(scope.row._id)"></el-button>
						</el-tooltip> -->
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
		<el-drawer :title="typeId ? '编辑类型' : '添加类型'" size="500px" :visible.sync="typeAddDrawer" direction="rtl"
			:append-to-body="true" :wrapperClosable="false" destroy-on-close :show-close="false"
			@open="typeAddDrawerOpen">
			<typeAddEdit :id="typeId" ref="typeAddEditRef" @closeDrawer="closeDrawer" @loadData="loadData">
			</typeAddEdit>
		</el-drawer>
	</div>
</template>

<script>
	const __name = 'wmzmall-message-type';
	export default {
		data() {
			return {
				advancedSearch: false,
				typeOptions: [{
						value: '',
						label: '全部'
					},
					{
						value: 1,
						label: '管理员'
					},
					{
						value: 2,
						label: '用户'
					}
				],
				stateOptions: [{
						value: '',
						label: '全部'
					},
					{
						value: 1,
						label: '显示'
					},
					{
						value: 0,
						label: '隐藏'
					}
				],
				req: {
					page: 1,
					rows: 10,
					orderby: 'sort asc',
					title: '',
					type: '',
					state: ''
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				searchBtnLoading: false,
				selectDatas: [],
				wxQrcodeUrl: '',
				bindLoading: false,
				unbindLoading: false,
				bindsLoading: false,
				popoverDisabled: true,
				removesBtnLoading: false,
				sortLastTime: null,
				typeAddDrawer: false,
				typeId: ''
			};
		},
		methods: {
			async loadData(callback) {
				return;
				this.tableLoading = true;

				await this.$db[__name]
					.whereif(this.req.title, {
						title: new RegExp(this.$api.filterRegexpKey(this.req.title), 'i')
					})
					.whereif(this.req.type, {
						type: this.req.type
					})
					.whereif(this.req.state !== '', {
						state: this.req.state
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			toAdd() {
				this.typeId = '';

				this.typeAddDrawer = true;
			},
			toEdit(id) {
				this.typeAddDrawer = true;

				this.typeId = id;

				if (this.$refs.typeAddEditRef) {
					this.$refs.typeAddEditRef.loadData();
				}
			},
			typeAddDrawerOpen() {
				if (this.$refs.typeAddEditRef) {
					this.$refs.typeAddEditRef.reset();
				}
			},
			closeDrawer() {
				this.typeAddDrawer = false;
			},
			bind(id) {
				this.bindLoading = true;
				this.$func.wmzadmin
					.call('message/wxQrcodeGet', {
							ids: [id]
						},
						false
					).then(res => {
						if (res.code == 200) {
							this.wxQrcodeUrl = res.datas.url;
						}
						this.bindLoading = false;
					});

				this.$refs.etbl.$el.querySelector('.el-table__body-wrapper').onscroll = () => {
					this.$refs['popoverRef' + id].doClose();
				}
			},
			unbind(row, item) {
				this.unbindLoading = true;
				this.$func.wmzadmin
					.call('message/unbind', {
							row: row,
							item: item
						},
						false
					).then(res => {
						if (res.code == 200) {
							this.$message({
								type: 'success',
								message: '操作成功!'
							});
							this.loadData();
						}
						this.unbindLoading = false;
					});
			},
			remove(id) {
				this.$confirm('此操作将永久删除该数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].remove(id).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
					});
				});
			},
			selectionChange(datas) {
				this.selectDatas = datas;
			},
			selectable(datas) {
				if (datas.type == 2) {
					return false;
				}

				return true;
			},
			binds() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要绑定的数据');
					return;
				}

				this.popoverDisabled = false;
			},
			popoverShow() {
				let ids = this.selectDatas.map(x => x._id);

				this.bindsLoading = true;
				this.$func.wmzadmin
					.call('message/wxQrcodeGet', {
							ids: ids
						},
						false
					).then(res => {
						if (res.code == 200) {
							this.wxQrcodeUrl = res.datas.url;
						}
						this.bindsLoading = false;
					});
			},
			popoverAfterLeave() {
				this.popoverDisabled = true;
			},
			removes() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要删除的数据');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将永久删除勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removesBtnLoading = true;
					this.$db[__name]
						.where({
							_id: this.$db.$cmd.in(ids)
						})
						.remove()
						.then(res => {
							if (res.code == 200) {
								this.loadData();
							}
							this.removesBtnLoading = false;
						});
				});
			},
			sortChange(newSort, oldSort, row) {
				if (!newSort) {
					this.$nextTick(() => {
						row.sort = oldSort;
					})
					return;
				}

				if (event && ['change', 'mouseup'].includes(event.type)) {
					this.sortUpdate(row);
					return;
				}

				if (this.sortLastTime !== null) {
					clearTimeout(this.sortLastTime)
				}

				this.sortLastTime = setTimeout(() => {
					this.sortUpdate(row)
				}, 500);
			},
			sortUpdate(row) {
				this.$db[__name].update(row._id, {
					sort: row.sort
				})
			},
			stateChange(row) {
				this.tableLoading = true;

				this.$db[__name].update(row._id, {
					state: row.state
				}, false).then(res => {
					if (res.code == 200) {
						this.tableLoading = false;
						return;
					}
					this.loadData();
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.type || this.req.state !== '') {
					this.advancedSearch = true;
				}
			}

			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.receive {
		width: max-content;
		border-radius: 50%;
	}

	.receive:hover .el-icon-minus {
		display: flex;
	}

	.receive .el-icon-minus,
	.receive .el-icon-loading {
		display: none;
		width: 30px;
		height: 30px;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		color: #fff;
		font-weight: 600;
		font-size: 16px;
	}

	.receive .el-icon-loading {
		font-weight: 0;
		display: flex;
	}
</style>
